from db_utils import con_my_sql
import pymysql
import gm_salt_sm3
from config import config_instance


# 获取用户管理数据库连接配置并使用
user_conn = pymysql.connect(**config_instance.user_conn_config)

def get_user_list():
    """
    获取所有用户信息。

    :return: 如果有用户信息，返回包含用户字典的列表；否则返回空列表
    """
    sql_code = "SELECT * FROM users"  # 修改查询语句，不再根据特定ID查询，而是查询所有用户
    cursor_ans = con_my_sql(user_conn, sql_code, ())
    # print(cursor_ans)
    if isinstance(cursor_ans, tuple) and issubclass(cursor_ans[0], Exception):
        print(f"Error getting all users: {cursor_ans[1]}")
        return []
    else:
        return cursor_ans


def create_user(username, password, email, unit):
    """
    创建新用户。

    :param username: 用户名
    :param password: 密码
    :param email: 邮箱
    :param unit: 单位
    :return: 如果创建成功，返回True；否则返回False
    """
    salt = gm_salt_sm3.generate_salt()
    pwd_salt_hash = gm_salt_sm3.hmac_with_salt(password, salt)
    sql_code = "INSERT INTO `users` (`Username`, `PasswordHash`, `Salt`, `Email`, `Unit`) VALUES (%s, %s, %s, %s, %s)"
    result = con_my_sql(user_conn, sql_code, (username, pwd_salt_hash, salt, email, unit))

    if isinstance(result, tuple) and issubclass(result[0], Exception):
        print(f"Error creating user: {result[1]}")
        return False
    else:
        return True


def delete_user(user_id):
    """
    删除用户。

    :param user_id: 用户ID
    :return: 如果删除成功，返回True；否则返回False
    """
    sql_code = "DELETE FROM `users` WHERE UserID = %s"
    result = con_my_sql(user_conn, sql_code, (user_id,))

    if isinstance(result, tuple) and issubclass(result[0], Exception):
        print(f"Error deleting user: {result[1]}")
        return False
    else:
        return True

def get_user_by_id(user_id):
    """
    根据用户ID获取用户信息。

    :param user_id: 用户ID
    :return: 如果找到用户，返回用户字典；否则返回None
    """
    sql_code = "SELECT * FROM users WHERE UserID = %s"
    cursor_ans = con_my_sql(user_conn, sql_code, (user_id,))

    if isinstance(cursor_ans, tuple) and issubclass(cursor_ans[0], Exception):
        print(f"Error getting user by id: {cursor_ans[1]}")
        return None
    else:
        if cursor_ans:
            user_data = cursor_ans[0]
        else:
            user_data = None
        return user_data

def get_user_by_email(email):
    """
    根据用户邮箱获取用户信息。

    :param email: 用户邮箱地址
    :return: 如果找到用户，返回用户字典；否则返回None
    """
    user_data = None
    try:
        sql_code = "SELECT * FROM users WHERE Email = %s"
        cursor_ans = con_my_sql(user_conn, sql_code, (email,))
        if cursor_ans:
            user_data = cursor_ans[0]
    except Exception as ex:
        print(ex)
    return user_data

def update_user_password(user_id, new_password):
    """
    更新用户的密码。

    :param user_id: 用户ID
    :param new_password: 新密码
    :return: 如果更新成功，返回True；否则返回False
    """
    salt = gm_salt_sm3.generate_salt()
    pwd_salt_hash = gm_salt_sm3.hmac_with_salt(new_password, salt)
    sql_code = "UPDATE `users` SET `PasswordHash` = %s, `Salt` = %s WHERE UserID = %s"
    result = con_my_sql(user_conn, sql_code, (pwd_salt_hash, salt, user_id))

    if isinstance(result, tuple) and issubclass(result[0], Exception):
        print(f"Error updating user password: {result[1]}")
        return False
    else:
        return True
